package com.jdkreader.concurrency.concurrent.game;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class Horse implements Runnable{

    private static int counter = 0;
    private final int id = counter++;

    //马跑过的步伐，用于模拟赛马
    private int strides = 0;

    private static CyclicBarrier barrier;

    public Horse(CyclicBarrier b){
        this.barrier = b;
    }

    public synchronized int getStrides(){
        return strides;
    }

    @Override
    public void run(){
        try{
            while(!Thread.interrupted()){
                synchronized(this){//这里加锁和getStrides()加锁如何理解？
                    strides += new Random().nextInt(3); //马每次跑0,1,2中的随机数
                }
                //当前线程执行完后，到达barrier（栅栏），所有线程到达栅栏后才会执行之后的操作
                barrier.await();
            }

        }catch(InterruptedException e){
            e.printStackTrace();
        }catch(BrokenBarrierException e){
            e.printStackTrace();
        }
    }

    //打印马跑的痕迹
    public String tracks(){
        StringBuilder s=new StringBuilder();
        for(int i=0;i<getStrides();i++){
            s.append("*");
        }
        return s.toString();
    }

    @Override
    public String toString() {
        return "Horse{" +
                "id=" + id +
                '}';
    }
}
